<template>
  <div class="register-container">
    <div class="register-box">
      <div class="logo">
        <span class="logo-cloud">忘记密码</span>
      </div>

      <div class="welcome-text">
        Forgot Password, Please Enter a New Password
      </div>

      <el-form :model="form" class="register-form" :rules="rules" ref="forgotPasswordFormRef">
        <el-form-item prop="email" class="form-item-spacing">
          <el-input
              v-model="form.email"
              placeholder="请输入完整邮箱地址"
              prefix-icon="el-icon-message"
          />
        </el-form-item>

        <el-form-item prop="verificationCode" class="form-item-spacing">
          <div class="code-input-wrapper">
            <el-input
                v-model="form.verification_code"
                placeholder="邮箱验证码"
                prefix-icon="el-icon-mobile"
                class="verification-input"
            />
            <el-button
                type="danger"
                class="send-code-btn"
                :disabled="isCountingDown"
                @click="sendVerificationCode"
                :loading="isSendingCode"
            >
              {{ countdown > 0 ? `${countdown}s后重发` : '发送' }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item prop="password" class="form-item-spacing">
          <el-input
              v-model="form.pass_word"
              placeholder="请输入新密码"
              type="password"
              prefix-icon="el-icon-lock"
              show-password
          />
        </el-form-item>

        <el-form-item prop="confirm_password" class="form-item-spacing">
          <el-input
              v-model="form.confirm_pass_word"
              placeholder="请再次输入新密码"
              type="password"
              prefix-icon="el-icon-lock"
              show-password
          />
        </el-form-item>

        <el-form-item class="form-item-spacing">
          <el-button
              type="danger"
              class="register-btn"
              @click="handleSubmit"
              :loading="isSubmitting"
          >
            提交
          </el-button>
        </el-form-item>
      </el-form>

      <div class="footer-links">
        <el-link @click="goToLogin">返回登录</el-link>
        <el-link @click="goToRegister">返回注册</el-link>
      </div>

      <div class="language-selector">
        <el-link>简体中文</el-link>
      </div>
    </div>

    <el-dialog
        v-model="resultDialogVisible"
        :title="resultDialogTitle"
        width="30%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
    >
      <span>{{ resultDialogMessage }}</span>
      <template #footer>
        <div style="text-align: center">
          <el-button
              v-if="resultDialogTitle === '操作成功'"
              @click="redirectImmediately"
          >
            点击立即跳转
          </el-button>
          <el-button
              v-else
              @click="resultDialogVisible = false"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { emailTask, PasswordTask } from '~/api/signupApi'

const router = useRouter()

const resultDialogVisible = ref(false)
const resultDialogTitle = ref('')
const resultDialogMessage = ref('')

const form = reactive({
  account: '',
  email: '',
  verification_code: '',
  pass_word: '',
  confirm_pass_word: ''
})

const validatePasswordConfirm = (rule: any, value: string, callback: any) => {
  if (value !== form.pass_word) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const rules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入邮箱'))
        } else if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value)) {
          callback(new Error('请输入有效的邮箱地址'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ],
  verification_code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  pass_word: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirm_pass_word: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validatePasswordConfirm, trigger: ['blur', 'change'] }
  ]
}

const forgotPasswordFormRef = ref<FormInstance>()
const isCountingDown = ref(false)
const countdown = ref(0)
const isSendingCode = ref(false)
const isSubmitting = ref(false)

const sendVerificationCode = async () => {
  if (!form.email) {
    showResultDialog(false, "请输入邮箱！")
    return
  }

  try {
    isSendingCode.value = true

    const formData = new FormData()
    formData.append('email', form.email)

    const response = await emailTask(formData)

    if (response.success) {
      showResultDialog(true, `${response.msg}，验证码有效期5分钟`)
      startCountdown()
    } else {
      showResultDialog(false, '邮箱验证码发送失败！')
    }
  } catch (error) {
    showResultDialog(false, '发送验证码时发生错误')
  } finally {
    isSendingCode.value = false
  }
}

const startCountdown = () => {
  isCountingDown.value = true
  countdown.value = 60

  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
      isCountingDown.value = false
    }
  }, 1000)
}

const handleSubmit = async () => {
  if (!forgotPasswordFormRef.value) return

  try {
    isSubmitting.value = true

    // 验证表单
    const valid = await forgotPasswordFormRef.value.validate()
    if (!valid) return

    // 检查验证码是否为空
    if (!form.verification_code) {
      showResultDialog(false, '请输入验证码')
      return
    }

    // 准备表单数据
    const formData = new FormData()

    formData.append('account', form.email)
    formData.append('email', form.email)
    formData.append('new_password', form.pass_word)
    formData.append('confirm_password', form.confirm_pass_word)
    formData.append('verification_code', form.verification_code)


    // 调用重置密码API
    const response = await PasswordTask(formData)

    if (response.success) {
      // 操作成功，显示倒计时弹窗
      showSuccessDialogWithCountdown()
    } else {
      showResultDialog(false, response.msg || '密码重置失败')
    }
  } catch (error: any) {
    console.error('Password reset error:', error)
    showResultDialog(false, error.message || '密码重置过程中发生错误')
  } finally {
    isSubmitting.value = false
  }
}

const successCountdown = ref(5)
let successTimer: number | null = null

const showSuccessDialogWithCountdown = () => {
  resultDialogTitle.value = '操作成功'
  resultDialogMessage.value = `密码重置成功，将在 ${successCountdown.value} 秒后自动跳转...`
  resultDialogVisible.value = true

  // 清除之前的计时器
  if (successTimer !== null) {
    clearInterval(successTimer)
    successTimer = null
  }

  // 开始倒计时
  successTimer = window.setInterval(() => {
    successCountdown.value--
    resultDialogMessage.value = `密码重置成功，将在 ${successCountdown.value} 秒后自动跳转登录页面...`

    if (successCountdown.value <= 0) {
      if (successTimer !== null) {
        clearInterval(successTimer)
        successTimer = null
      }
      router.push('/login')
      resultDialogVisible.value = false
    }
  }, 1000)
}

// 立即跳转函数
const redirectImmediately = () => {
  if (successTimer !== null) {
    clearInterval(successTimer)
    successTimer = null
  }
  router.push('/login')
  resultDialogVisible.value = false
}

const goToLogin = () => {
  router.push('/login')
}

const goToRegister = () => {
  router.push('/register')
}

const showResultDialog = (isSuccess: boolean, message: string) => {
  resultDialogTitle.value = isSuccess ? 'Success' : 'Error'
  resultDialogMessage.value = message
  resultDialogVisible.value = true
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  margin: 0 200px 0px 200px;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.register-box {
  width: 550px;
  padding: 40px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
}

.logo {
  margin-bottom: 10px;
  font-size: 32px;
  font-weight: bold;
}

.logo-cloud {
  color: #606266;
}

.welcome-text {
  margin-bottom: 30px;
  color: #909399;
  font-size: 14px;
}

.register-form {
  margin-top: 10px;
}

.form-item-spacing {
  margin-bottom: 22px;
}

.code-input-wrapper {
  display: flex;
  gap: 10px;
  width: 100%;
}

.verification-input {
  flex: 1;
}

.send-code-btn {
  width: 120px;
  background-color: #1b9382;
  border: none;
}

.register-btn {
  width: 100%;
  margin-top: 5px;
  background-color: #1b9382;
  border: none;
}

.footer-links {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.language-selector {
  margin-top: 30px;
  text-align: center;
}

.el-link {
  margin: 0 10px;
}
</style>